package test.proxy;

import java.lang.reflect.Method;

import org.mockito.cglib.proxy.Enhancer;
import org.mockito.cglib.proxy.MethodInterceptor;
import org.mockito.cglib.proxy.MethodProxy;

public class CgliDynomicProxy implements MethodInterceptor {

	public Object newProxy(Class clazz) {
		Enhancer enhancer = new Enhancer();// 该类用于生成代理对象
		enhancer.setSuperclass(clazz);// 设置父类
		enhancer.setCallback(this);// 设置回调对象为本身
		return enhancer.create();// 通过字节码技术动态创建子类实例
	}

	@Override
	public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {

		Object result = methodProxy.invokeSuper(proxy, args);// 调用原始对象的方法

		return result;
	}

	/**
	 * CGLIB 动态代理
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

		CgliDynomicProxy cglibProxy = new CgliDynomicProxy();
		CglibTargetObj proxy = (CglibTargetObj) cglibProxy.newProxy(CglibTargetObj.class);

		proxy.sayHello();

		System.out.println("\n---------------------------------\n");

		String str = proxy.sayHelloWithReturnValue();
		System.out.println("str = " + str);
	}

}
